#!/usr/bin/env python3
"""
GSI Wiki Generator - Main Generator Class

Professional wiki generator for GSI DRP-4DVar implementation using 
codebase-rag search and Claude AI integration.
"""

import json
import subprocess
import logging
import tempfile
import os
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional

from .config import WikiConfig


class GSIWikiGenerator:
    """Enhanced wiki generator using direct codebase-rag commands"""
    
    def __init__(self, config: Optional[WikiConfig] = None):
        """Initialize generator with configuration"""
        self.config = config or WikiConfig()
        self.config.validate()
        
        # Set up paths
        self.input_dir = self.config.get_absolute_input_path()
        self.output_dir = self.config.get_absolute_output_path()
        self.outline_file = self.config.get_outline_path()
        
        # Load outline data
        self.outline_data = self._load_outline()
        
        # Create organized directory structure
        self.base_dir = self.output_dir
        self.logs_dir = self.base_dir / "logs"
        self.search_results_dir = self.base_dir / "search_results"
        self.claude_answers_dir = self.base_dir / "claude_answers"
        self.final_output_dir = self.base_dir / "final_wiki"
        
        # Create directories
        for directory in [self.logs_dir, self.search_results_dir, self.claude_answers_dir, self.final_output_dir]:
            directory.mkdir(parents=True, exist_ok=True)
        
        # Configure organized logging
        self._setup_logging()
        
        # Set file paths
        self.search_cache_file = self.search_results_dir / "codebase_rag_search_results.json"
        self.search_context_file = self.search_results_dir / "codebase_search_context.txt"
        self.progress_cache_file = self.base_dir / "progress_cache.json"
        
        # Load existing progress
        self.progress_cache = self._load_progress_cache()
        
        # Log initialization
        self.logger.info(f"GSI Wiki Generator initialized")
        self.logger.info(f"Input directory: {self.input_dir}")
        self.logger.info(f"Output directory: {self.output_dir}")
        self.logger.info(f"Outline file: {self.outline_file}")
        
    def _setup_logging(self):
        """Setup organized logging configuration"""
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        log_file = self.logs_dir / f"gsi_wiki_generator_{timestamp}.log"
        
        # Configure logging
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file),
                logging.StreamHandler()
            ],
            force=True  # Override any existing configuration
        )
        self.logger = logging.getLogger(__name__)
        self.logger.info(f"Logging initialized - Log file: {log_file}")
    
    def _load_progress_cache(self) -> Dict[str, Any]:
        """Load existing progress cache to resume from where we left off"""
        if self.progress_cache_file.exists():
            try:
                with open(self.progress_cache_file, 'r', encoding='utf-8') as f:
                    cache = json.load(f)
                self.logger.info(f"Progress cache loaded: {len(cache.get('completed_searches', []))} searches, {len(cache.get('completed_questions', []))} questions completed")
                return cache
            except Exception as e:
                self.logger.warning(f"Could not load progress cache: {str(e)}")
        
        # Return empty cache structure
        return {
            "completed_searches": [],
            "completed_questions": [],
            "search_results": {},
            "claude_answers": {},
            "last_updated": None,
            "session_id": datetime.now().strftime("%Y%m%d_%H%M%S"),
            "input_directory": str(self.input_dir)
        }
    
    def _save_progress_cache(self) -> None:
        """Save current progress to cache"""
        self.progress_cache["last_updated"] = datetime.now().isoformat()
        self.progress_cache["input_directory"] = str(self.input_dir)
        
        with open(self.progress_cache_file, 'w', encoding='utf-8') as f:
            json.dump(self.progress_cache, f, ensure_ascii=False, indent=2)
        
        self.logger.info(f"Progress cache saved: {len(self.progress_cache.get('completed_searches', []))} searches, {len(self.progress_cache.get('completed_questions', []))} questions")
    
    def reset_progress_cache(self) -> None:
        """Reset progress cache to start fresh"""
        self.progress_cache = {
            "completed_searches": [],
            "completed_questions": [],
            "search_results": {},
            "claude_answers": {},
            "last_updated": None,
            "session_id": datetime.now().strftime("%Y%m%d_%H%M%S"),
            "input_directory": str(self.input_dir)
        }
        self._save_progress_cache()
        self.logger.info("Progress cache has been reset")
    
    def _ensure_codebase_indexed(self) -> bool:
        """Ensure the input directory is indexed by codebase-rag"""
        self.logger.info(f"Checking codebase index for: {self.input_dir}")
        
        try:
            # Check if index exists by trying a simple search
            result = subprocess.run([
                "codebase-rag", "search", "--max-results", "1", "test"
            ], capture_output=True, text=True, cwd=str(self.input_dir))
            
            if result.returncode == 0:
                self.logger.info("Codebase index exists and is ready")
                return True
            
            # Index not ready, create it
            self.logger.info(f"Creating codebase index for: {self.input_dir}")
            result = subprocess.run([
                "codebase-rag", "index", "."
            ], capture_output=True, text=True, timeout=300, cwd=str(self.input_dir))
            
            if result.returncode == 0:
                self.logger.info("Codebase indexing completed successfully")
                return True
            else:
                self.logger.error(f"Codebase indexing failed: {result.stderr}")
                return False
                
        except subprocess.TimeoutExpired:
            self.logger.error("Codebase indexing timed out")
            return False
        except Exception as e:
            self.logger.error(f"Error during codebase indexing: {str(e)}")
            return False
    
    def _load_outline(self) -> Dict[str, Any]:
        """Load the existing wiki outline"""
        with open(self.outline_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    
    def _run_codebase_rag_search(self, query: str) -> List[Dict]:
        """Run codebase-rag search command and return results"""
        
        cmd = [
            "codebase-rag", "search", 
            "--max-results", str(self.config.max_results),
            "--min-score", str(self.config.min_score),
            query
        ]
        
        self.logger.info(f"Running codebase-rag search: {query}")
        
        try:
            # Run search in the input directory context
            result = subprocess.run(
                cmd, 
                capture_output=True, 
                text=True, 
                encoding='utf-8',
                timeout=self.config.search_timeout,
                cwd=str(self.input_dir)  # Important: run in input directory
            )
            
            if result.returncode == 0:
                output = result.stdout.strip()
                self.logger.info(f"Search successful: {len(output)} characters returned")
                
                # Parse codebase-rag output format
                parsed_results = self._parse_codebase_rag_output(output)
                
                # Store structured results
                return [{
                    "query": query,
                    "raw_output": output,
                    "parsed_results": parsed_results,
                    "search_params": {"max_results": self.config.max_results, "min_score": self.config.min_score},
                    "result_count": len(parsed_results),
                    "search_directory": str(self.input_dir)
                }]
            else:
                self.logger.error(f"codebase-rag search failed: {result.stderr}")
                return []
                
        except subprocess.TimeoutExpired:
            self.logger.error(f"codebase-rag search timed out for query: {query}")
            return []
        except Exception as e:
            self.logger.error(f"Error running codebase-rag search: {str(e)}")
            return []
    
    def _parse_codebase_rag_output(self, output: str) -> List[Dict]:
        """Parse codebase-rag search output into structured results"""
        
        parsed_results = []
        
        try:
            # Split output into individual results
            lines = output.split('\n')
            current_result = {}
            in_code_block = False
            code_lines = []
            
            for line in lines:
                # Match result headers like "**1. filename.ext** (lines X-Y) - Score: Z"
                if line.startswith('**') and '. ' in line and '**' in line:
                    # Save previous result if exists
                    if current_result:
                        if code_lines:
                            current_result['code_snippet'] = '\n'.join(code_lines)
                        parsed_results.append(current_result)
                    
                    # Parse new result header
                    try:
                        # Extract filename, line range, and score
                        parts = line.split(' - Score: ')
                        if len(parts) == 2:
                            score = float(parts[1])
                            header_part = parts[0]
                            
                            # Extract filename and lines
                            if '** (lines ' in header_part:
                                file_part, lines_part = header_part.split('** (lines ')
                                filename = file_part.replace('**', '').split('. ', 1)[1]
                                line_range = lines_part.rstrip(')')
                            else:
                                filename = header_part.replace('**', '').split('. ', 1)[1]
                                line_range = "unknown"
                                score = 0.0
                            
                            current_result = {
                                'filename': filename,
                                'line_range': line_range,
                                'score': score,
                                'code_snippet': ''
                            }
                            code_lines = []
                            in_code_block = False
                    except (ValueError, IndexError) as e:
                        self.logger.warning(f"Could not parse result header: {line}")
                        continue
                
                # Handle code blocks
                elif line.strip() == '```':
                    in_code_block = not in_code_block
                elif in_code_block:
                    code_lines.append(line)
            
            # Add the last result
            if current_result:
                if code_lines:
                    current_result['code_snippet'] = '\n'.join(code_lines)
                parsed_results.append(current_result)
        
        except Exception as e:
            self.logger.error(f"Error parsing codebase-rag output: {str(e)}")
            # Return raw output as fallback
            parsed_results = [{"raw_content": output, "parse_error": str(e)}]
        
        self.logger.info(f"Parsed {len(parsed_results)} results from codebase-rag output")
        return parsed_results
    
    def get_progress_report(self) -> Dict[str, Any]:
        """Get current progress report"""
        # Count total questions from outline
        total_questions = 0
        for section in self.outline_data['sections']:
            total_questions += len(section.get('practical_questions', []))
            for subsection in section.get('subsections', []):
                total_questions += len(subsection.get('practical_questions', []))
        
        # Generate search queries to get total count
        all_questions = []
        for section in self.outline_data['sections']:
            all_questions.extend(section.get('practical_questions', []))
            for subsection in section.get('subsections', []):
                all_questions.extend(subsection.get('practical_questions', []))
        
        search_queries = self._generate_search_queries(all_questions)
        total_searches = len(search_queries)
        
        completed_searches = len(self.progress_cache.get("completed_searches", []))
        completed_questions = len(self.progress_cache.get("completed_questions", []))
        
        return {
            "total_searches": total_searches,
            "completed_searches": completed_searches,
            "remaining_searches": total_searches - completed_searches,
            "search_progress_percent": (completed_searches / total_searches * 100) if total_searches > 0 else 0,
            "total_questions": total_questions,
            "completed_questions": completed_questions,
            "remaining_questions": total_questions - completed_questions,
            "question_progress_percent": (completed_questions / total_questions * 100) if total_questions > 0 else 0,
            "last_updated": self.progress_cache.get("last_updated"),
            "session_id": self.progress_cache.get("session_id"),
            "input_directory": self.progress_cache.get("input_directory", str(self.input_dir))
        }
    
    def _generate_search_queries(self, questions: List[str]) -> List[str]:
        """Generate targeted search queries based on practical questions"""
        
        # Map questions to specific search terms
        query_mapping = {
            "如何在现有GSI系统中集成DRP-4DVar模块": [
                "DRP-4DVar integration GSI",
                "drp4dvar module initialization",
                "GSI main driver modification",
                "namelist ldrp4dvar configuration"
            ],
            "DRP-4DVar相比传统4DVar在计算效率上的具体优势": [
                "DRP-4DVar performance comparison",
                "4DVar computational cost efficiency",
                "adjoint model avoidance",
                "ensemble perturbation projection"
            ],
            "如何识别和解决diag_conv文件中的NaN值问题": [
                "diagnostic file NaN values",
                "diag_conv file validation",
                "GSI EnKF interface problems",
                "observation space ensemble spread"
            ],
            "DRP-4DVar如何通过EOF分析处理集合扰动": [
                "EOF analysis ensemble perturbations",
                "empirical orthogonal functions DRP",
                "ensemble covariance matrix",
                "dimensionality reduction projection"
            ],
            "如何配置Ollama模型进行GSI/EnKF代码注释": [
                "automated code commentary system",
                "Ollama model configuration",
                "git diff patch generation",
                "parallel processing workers"
            ],
            "如何设计测试用例验证DRP-3DVar相对标准3DVar的优势": [
                "DRP-3DVar validation testing",
                "3DVar performance comparison",
                "test case design verification",
                "analysis accuracy metrics"
            ]
        }
        
        # Generate comprehensive search queries
        search_queries = []
        
        # Add specific mapped queries
        for question in questions:
            if any(key in question for key in query_mapping.keys()):
                for key, queries in query_mapping.items():
                    if key in question:
                        search_queries.extend(queries)
        
        # Add comprehensive GSI/DRP-4DVar queries
        general_queries = [
            "GSI DRP-4DVar implementation",
            "ensemble data assimilation EnKF",
            "variational data assimilation 3DVar 4DVar",
            "background error covariance matrix",
            "observation operator H matrix",
            "diagnostic file generation diag_conv",
            "EnKF ensemble kalman filter",
            "automated code commentary git diff",
            "parallel processing MPI",
            "cmake build system configuration",
            "namelist configuration ldrp4dvar",
            "EOF analysis empirical orthogonal",
            "projection matrix dimensionality reduction",
            "time window assimilation",
            "gradient calculation optimization",
            "fortran interface GSI EnKF",
            "quality control observation",
            "computational efficiency performance",
            "NaN value debugging troubleshooting",
            "file format NetCDF binary"
        ]
        
        search_queries.extend(general_queries)
        
        # Remove duplicates while preserving order
        return list(dict.fromkeys(search_queries))
    
    def generate_wiki(self) -> str:
        """Generate enhanced wiki using codebase-rag search results"""
        
        self.logger.info("开始使用codebase-rag生成增强版wiki")
        
        # Ensure codebase is indexed
        if not self._ensure_codebase_indexed():
            raise RuntimeError("Failed to index codebase - cannot proceed with wiki generation")
        
        # Show initial progress
        progress = self.get_progress_report()
        self.logger.info(f"Starting generation - Searches: {progress['completed_searches']}/{progress['total_searches']} ({progress['search_progress_percent']:.1f}%), Questions: {progress['completed_questions']}/{progress['total_questions']} ({progress['question_progress_percent']:.1f}%)")
        
        # Step 1: Collect search results
        self.logger.info("步骤1: 收集代码库搜索结果")
        search_results = self._collect_search_results_for_questions()
        self._save_search_results(search_results)
        
        # Step 2: Generate answers using Claude with background
        self.logger.info("步骤2: 使用Claude生成技术解答")
        enhanced_answers = self._generate_claude_answers()
        
        # Save all answers summary
        self._save_all_answers_summary(enhanced_answers)
        
        # Step 3: Generate final wiki
        self.logger.info("步骤3: 生成最终wiki文档")
        wiki_content = self._build_final_wiki(enhanced_answers, search_results)
        
        return wiki_content
    
    def _collect_search_results_for_questions(self) -> Dict[str, List[Dict]]:
        """Collect codebase-rag search results for all practical questions"""
        
        all_questions = []
        search_results = {}
        
        # Extract all practical questions from the outline
        for section in self.outline_data['sections']:
            questions = section.get('practical_questions', [])
            all_questions.extend(questions)
            
            for subsection in section.get('subsections', []):
                sub_questions = subsection.get('practical_questions', [])
                all_questions.extend(sub_questions)
        
        self.logger.info(f"Found {len(all_questions)} practical questions to research")
        
        # Define search queries based on practical questions
        search_queries = self._generate_search_queries(all_questions)
        
        # Run searches and collect results
        for query in search_queries:
            # Check if this search was already completed
            if query in self.progress_cache.get("completed_searches", []):
                self.logger.info(f"Skipping already completed search: {query}")
                # Load cached results if available
                if query in self.progress_cache.get("search_results", {}):
                    search_results[query] = self.progress_cache["search_results"][query]
                continue
                
            self.logger.info(f"Running new search: {query}")
            results = self._run_codebase_rag_search(query)
            search_results[query] = results
            
            # Update cache
            if "completed_searches" not in self.progress_cache:
                self.progress_cache["completed_searches"] = []
            if "search_results" not in self.progress_cache:
                self.progress_cache["search_results"] = {}
                
            self.progress_cache["completed_searches"].append(query)
            self.progress_cache["search_results"][query] = results
            self._save_progress_cache()
        
        return search_results
    
    def save_wiki(self, output_file: str = "gsi_drp4dvar_wiki.md") -> None:
        """Save the enhanced wiki with codebase-rag integration"""
        
        enhanced_wiki = self.generate_wiki()
        
        # Save to final output directory
        final_wiki_file = self.final_output_dir / output_file
        
        with open(final_wiki_file, 'w', encoding='utf-8') as f:
            f.write(enhanced_wiki)
        
        self.logger.info(f"Enhanced wiki saved to: {final_wiki_file}")
        
        # Create directory summary
        self._create_directory_summary()
        
        return str(final_wiki_file)
    
    def _generate_claude_answers(self) -> Dict[str, str]:
        """Generate Claude answers for all questions"""
        from .claude_integration import ClaudeIntegration
        
        # Extract questions
        all_questions = []
        for section in self.outline_data['sections']:
            all_questions.extend(section.get('practical_questions', []))
            for subsection in section.get('subsections', []):
                all_questions.extend(subsection.get('practical_questions', []))
        
        # Initialize Claude integration
        claude = ClaudeIntegration(self.config, self.claude_answers_dir, self.search_context_file)
        
        enhanced_answers = {}
        
        for question in all_questions:
            # Check if this question was already answered
            if question in self.progress_cache.get("completed_questions", []):
                self.logger.info(f"Skipping already answered question: {question[:50]}...")
                # Load cached answer if available
                if question in self.progress_cache.get("claude_answers", {}):
                    enhanced_answers[question] = self.progress_cache["claude_answers"][question]
                continue
                
            self.logger.info(f"Processing new question: {question[:50]}...")
            answer = claude.call_claude_with_background(question)
            enhanced_answers[question] = answer
            
            # Update cache
            if "completed_questions" not in self.progress_cache:
                self.progress_cache["completed_questions"] = []
            if "claude_answers" not in self.progress_cache:
                self.progress_cache["claude_answers"] = {}
                
            self.progress_cache["completed_questions"].append(question)
            self.progress_cache["claude_answers"][question] = answer
            self._save_progress_cache()
        
        return enhanced_answers
    
    def _save_search_results(self, search_results: Dict[str, List[Dict]]) -> None:
        """Save search results to file for Claude to use"""
        
        with open(self.search_cache_file, 'w', encoding='utf-8') as f:
            json.dump(search_results, f, ensure_ascii=False, indent=2)
        
        self.logger.info(f"Search results saved to {self.search_cache_file}")
        
        # Also create a readable text file for Claude
        with open(self.search_context_file, 'w', encoding='utf-8') as f:
            f.write(f"# GSI DRP-4DVar Codebase Search Results\n")
            f.write(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"Search Parameters: --max-results {self.config.max_results} --min-score {self.config.min_score}\n")
            f.write(f"Search Directory: {self.input_dir}\n\n")
            
            total_results = 0
            for query, results in search_results.items():
                f.write(f"## Search Query: {query}\n\n")
                
                for i, result in enumerate(results, 1):
                    f.write(f"### Result Set {i}\n")
                    
                    # Write parsed results if available
                    if 'parsed_results' in result and result['parsed_results']:
                        for j, parsed in enumerate(result['parsed_results'], 1):
                            f.write(f"#### {j}. {parsed.get('filename', 'Unknown file')}\n")
                            if 'line_range' in parsed:
                                f.write(f"**Lines**: {parsed['line_range']}\n")
                            if 'score' in parsed:
                                f.write(f"**Score**: {parsed['score']:.3f}\n")
                            if 'code_snippet' in parsed:
                                f.write(f"```\n{parsed['code_snippet']}\n```\n\n")
                            total_results += 1
                    else:
                        # Fallback to raw output
                        f.write(f"```\n{result.get('raw_output', 'No output')}\n```\n\n")
                        total_results += 1
                
                f.write("---\n\n")
            
            f.write(f"\n**Summary**: {len(search_results)} queries executed, {total_results} total results found\n")
        
        self.logger.info(f"Readable search context saved to {self.search_context_file}")
    
    def _save_all_answers_summary(self, answers: Dict[str, str]) -> None:
        """Save summary of all Claude answers"""
        summary_file = self.claude_answers_dir / "answers_summary.json"
        
        with open(summary_file, 'w', encoding='utf-8') as f:
            json.dump(answers, f, ensure_ascii=False, indent=2)
        
        self.logger.info(f"All answers summary saved to: {summary_file}")
    
    def _build_final_wiki(self, answers: Dict[str, str], search_results: Dict[str, List[Dict]]) -> str:
        """Build the final wiki document with all enhancements"""
        
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        toc_entries = []
        
        wiki_lines = []
        
        # Header
        wiki_lines.append("# GSI DRP-4DVar实施指南 - Codebase-RAG增强版")
        wiki_lines.append(f"\n生成时间: {current_time}")
        wiki_lines.append("基于codebase: comGSIv3.7_EnKFv1.3") 
        wiki_lines.append("搜索引擎: codebase-rag直接命令行工具")
        wiki_lines.append(f"搜索目录: {self.input_dir}")
        wiki_lines.append(f"搜索参数: --max-results {self.config.max_results} --min-score {self.config.min_score}")
        wiki_lines.append(f"搜索查询数量: {len(search_results)}")
        wiki_lines.append(f"技术解答数量: {len(answers)}")
        
        # Calculate total results found
        total_found = sum(
            len(result_list[0].get('parsed_results', [])) if result_list else 0
            for result_list in search_results.values()
        )
        wiki_lines.append(f"代码片段总数: {total_found}\n")
        
        # Overview
        wiki_lines.append(self.outline_data['overview'])
        wiki_lines.append("")
        
        # Build TOC and content
        for section in self.outline_data['sections']:
            section_id = f"section-{abs(hash(section['title'])) % 10000:04d}"
            toc_entries.append(f"- [{section['title']}](#{section_id})")
            
            # Add subsections to TOC
            for subsection in section.get('subsections', []):
                sub_id = f"subsection-{abs(hash(subsection['title'])) % 10000:04d}"
                toc_entries.append(f"  - [{subsection['title']}](#{sub_id})")
        
        # Insert TOC
        wiki_lines.append("## 目录\n")
        wiki_lines.extend(toc_entries)
        wiki_lines.append("")
        
        # Generate sections with enhanced content
        for section in self.outline_data['sections']:
            section_content = self._build_section_content(section, answers, 1)
            wiki_lines.append(section_content)
            wiki_lines.append("")
        
        # Add search results appendix
        wiki_lines.append("---")
        wiki_lines.append("## 附录: 代码库搜索结果统计")
        wiki_lines.append("")
        wiki_lines.append(f"- **搜索查询总数**: {len(search_results)}")
        wiki_lines.append(f"- **技术解答数量**: {len(answers)}")
        wiki_lines.append(f"- **代码片段总数**: {total_found}")
        wiki_lines.append(f"- **搜索参数**: --max-results {self.config.max_results} --min-score {self.config.min_score}")
        wiki_lines.append(f"- **搜索目录**: {self.input_dir}")
        wiki_lines.append(f"- **搜索结果文件**: {self.search_context_file}")
        wiki_lines.append(f"- **缓存文件**: {self.search_cache_file}")
        wiki_lines.append(f"- **Claude答案目录**: {self.claude_answers_dir}")
        wiki_lines.append(f"- **日志目录**: {self.logs_dir}")
        wiki_lines.append("")
        
        # Add top result files summary
        file_count = {}
        for result_list in search_results.values():
            if result_list:
                for parsed in result_list[0].get('parsed_results', []):
                    filename = parsed.get('filename', 'Unknown')
                    file_count[filename] = file_count.get(filename, 0) + 1
        
        if file_count:
            wiki_lines.append("### 主要引用文件:")
            for filename, count in sorted(file_count.items(), key=lambda x: x[1], reverse=True)[:10]:
                wiki_lines.append(f"- `{filename}` ({count} 次引用)")
            wiki_lines.append("")
        
        return "\n".join(wiki_lines)
    
    def _build_section_content(self, section: Dict[str, Any], answers: Dict[str, str], level: int) -> str:
        """Build section content with enhanced answers"""
        
        section_id = f"section-{abs(hash(section['title'])) % 10000:04d}"
        content_lines = []
        
        # Section header
        content_lines.append(f"<a id='{section_id}'></a>")
        content_lines.append(f"{'#' * level} {section['title']}")
        content_lines.append("")
        
        # Content description
        if section.get('content_description'):
            content_lines.append(f"**内容描述**: {section['content_description']}")
            content_lines.append("")
        
        # Implementation focus
        if section.get('implementation_focus'):
            content_lines.append("**实施要点**:")
            for focus in section['implementation_focus']:
                content_lines.append(f"- {focus}")
            content_lines.append("")
        
        # Enhanced Q&A section
        if section.get('practical_questions'):
            content_lines.append("## 🔍 基于代码库分析的实践问题解答")
            content_lines.append("")
            
            for question in section['practical_questions']:
                content_lines.append(f"### ❓ {question}")
                content_lines.append("")
                
                if question in answers:
                    content_lines.append("**📋 详细技术解答** (基于codebase-rag搜索):")
                    content_lines.append("")
                    content_lines.append(answers[question])
                    content_lines.append("")
                else:
                    content_lines.append("*[基于代码库搜索的解答生成中...]*")
                    content_lines.append("")
        
        # Code references
        if section.get('code_references'):
            content_lines.append("**📁 相关代码文件**:")
            for ref in section['code_references']:
                content_lines.append(f"- `{ref}`")
            content_lines.append("")
        
        # Process subsections
        for subsection in section.get('subsections', []):
            subsection_content = self._build_section_content(subsection, answers, level + 1)
            content_lines.append(subsection_content)
        
        return "\n".join(content_lines)
    
    def _create_directory_summary(self) -> None:
        """Create a summary of all output files and directories"""
        summary_file = self.base_dir / "README.md"
        
        with open(summary_file, 'w', encoding='utf-8') as f:
            f.write("# GSI DRP-4DVar Codebase-RAG Enhanced Wiki Output\n\n")
            f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"输入目录: {self.input_dir}\n")
            f.write(f"输出目录: {self.output_dir}\n\n")
            
            f.write("## 目录结构\n\n")
            f.write("```\n")
            f.write(f"{self.base_dir.name}/\n")
            f.write("├── logs/                    # 处理日志文件\n")
            f.write("├── search_results/          # codebase-rag 搜索结果\n")
            f.write("├── claude_answers/          # Claude 生成的技术解答\n")
            f.write("├── final_wiki/              # 最终生成的wiki文档\n")
            f.write("└── README.md               # 本说明文件\n")
            f.write("```\n\n")
            
            f.write("## 文件说明\n\n")
            f.write("### 搜索结果目录 (search_results/)\n")
            f.write("- `codebase_rag_search_results.json` - 完整搜索结果JSON缓存\n")
            f.write("- `codebase_search_context.txt` - 人类可读的搜索结果文本\n\n")
            
            f.write("### Claude答案目录 (claude_answers/)\n")
            f.write("- 每个问题的独立答案文件 (.md格式)\n")
            f.write("- `answers_summary.json` - 所有答案的JSON汇总\n\n")
            
            f.write("### 日志目录 (logs/)\n")
            f.write("- 带时间戳的详细处理日志文件\n\n")
            
            f.write("### 最终wiki目录 (final_wiki/)\n")
            f.write("- 完整的GSI DRP-4DVar实施指南wiki文档\n\n")
            
            f.write("## 配置信息\n\n")
            f.write(f"- **搜索参数**: --max-results {self.config.max_results} --min-score {self.config.min_score}\n")
            f.write(f"- **超时设置**: Claude {self.config.claude_timeout}s, 搜索 {self.config.search_timeout}s\n")
            f.write(f"- **缓存状态**: {'启用' if self.config.enable_cache else '禁用'}\n\n")
            
            f.write("## 使用说明\n\n")
            f.write("1. 查看 `final_wiki/` 目录中的主要wiki文档\n")
            f.write("2. 参考 `claude_answers/` 目录中的详细技术解答\n")
            f.write("3. 检查 `search_results/` 目录中的原始搜索数据\n")
            f.write("4. 查看 `logs/` 目录中的处理日志了解生成过程\n")
        
        self.logger.info(f"Directory summary created: {summary_file}")